﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using FtpWebRole.Entities;
using FtpWorkerRole;
using FtpWorkerRole.FtpServer;

namespace FtpWebRole
{
    public partial class Monitor : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            LoadConfiguration();
            LoadPerformance();
            LoadConnections();
        }

        private void LoadConfiguration()
        {
            //TODO:
        }

        private void LoadPerformance()
        {
            // obtain all the records
            var ctx = new PerformanceContext(CloudStorageAccount.FromConfigurationSetting("DataConnectionString"));
            DateTime ago = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(5));
            var records = (from r in ctx.Records
                           where r.Timestamp > ago
                           select r)
                .AsTableServiceQuery().Execute().ToList(); // DataServiceQuery only returns 1,000 records

            // only select the latest one
            string val;
            List<PerformanceEntity> list;
            list = records.Where(r => r.CounterName == PerformanceSpecifier.ProcessorTime).ToList();
            val = (list.Count == 0) ? "?" : string.Format("{0:F2} %", list.OrderBy(e => e.Timestamp).Last().CounterValue);
            LblProcessorTime.Text = val;

            list = records.Where(r => r.CounterName == PerformanceSpecifier.MemoryAvailableBytes).ToList();
            val = (list.Count == 0) ? "?" : list.OrderBy(e => e.Timestamp).Last().CounterValue;
            LblMemAvailable.Text = string.Format("{0} bytes available, ", val);

            list = records.Where(r => r.CounterName == PerformanceSpecifier.MemoryCommittedBytes).ToList();
            val = (list.Count == 0) ? "?" : list.OrderBy(e => e.Timestamp).Last().CounterValue;
            LblMemCommitted.Text = string.Format("{0} bytes committed", val);

            // there may be multiple NICs
            var nics = (from r in records where r.CounterName.Contains("Network Interface") 
                        let pos1 = r.CounterName.IndexOf('(')
                        let pos2 = r.CounterName.IndexOf(')')
                        select r.CounterName.Substring(pos1 + 1, pos2 - pos1 - 1)).Distinct().ToList();
            TblNetwork.Rows.Clear();
            if (nics.Count == 0)
            {
                TableRow tr = new TableRow();
                tr.Cells.Add(new TableCell() { Text = "?" });
                TblNetwork.Rows.Add(tr);
                return;
            }

            nics.Sort();
            foreach (string nic in nics)
            {
                var l = (from r in records
                            where r.CounterName == PerformanceSpecifier.NetworkBytesSent.Replace("*", nic)
                            orderby r.Timestamp
                            select r.CounterValue).ToList();
                string send = (l.Count == 0) ? "?" : l.Last();
                l = (from r in records
                            where r.CounterName == PerformanceSpecifier.NetworkBytesSent.Replace("*", nic)
                            orderby r.Timestamp
                            select r.CounterValue).ToList();
                string recv = (l.Count == 0) ? "?" : l.Last();

                TableRow tr = new TableRow();
                tr.Cells.Add(new TableCell() { Text = "{"+nic+"}" });
                tr.Cells.Add(new TableCell() {
                    Text = string.Format("{0} bytes sent/sec, {0} bytes received/sec", send, recv)});
                TblNetwork.Rows.Add(tr);
            }
        }

        public void LoadConnections()
        {
            // read from the table
            var ctx = new ConnectionContext(
                CloudStorageAccount.FromConfigurationSetting("DataConnectionString"));
            var list = ctx.ConnectionEntities.ToList();

            // show in the table
            if (list.Count == 0)
            {
                GrdvCnnt.Visible = false;
                LblCnnt.Text = "No live connection exists";
            }
            else
            {
                LblCnnt.Text = string.Format("Total = {0}", list.Count);
                GrdvCnnt.DataSource = list;
                GrdvCnnt.DataBind();

                GrdvCnnt.Visible = true;
            }
        }
    }
}